<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close" :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="60px">
      <el-form-item label="编码" prop="productCode">
        <el-input v-model.trim="form.productCode" autocomplete="off" maxlength="50" placeholder="请输入产品编码"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="productName">
        <el-input v-model.trim="form.productName" autocomplete="off" maxlength="50" placeholder="请输入产品名称"></el-input>
      </el-form-item>
      <el-form-item label="类别" prop="categoryId">
        <treeselect
          v-model="form.categoryId"
          :options="options"
          :disable-branch-nodes="false"
          :show-count="true"
          :normalizer="normalizer"
          :flatten-search-results="false"
          noOptionsText="无类别可选"
          placeholder="请选择上级"
          @select="handleNodeClick"
        />
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input v-model.trim="form.spec" autocomplete="off" maxlength="50" placeholder="请输入规格"></el-input>
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model.trim="form.model" autocomplete="off" maxlength="50" placeholder="请输入型号"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="unitName">
        <el-input v-model.trim="form.unitName" autocomplete="off" maxlength="10" placeholder="请输入单位">
          <template slot="append"><el-button icon="el-icon-search" @click="openUnit"></el-button></template>
        </el-input>
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input
          v-model.trim="form.price"
          autocomplete="off"
          maxlength="10"
          placeholder="请输入单价"
          oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
    <unit ref="unit" @fetch-data="saveUnitData"></unit>
  </el-dialog>
</template>

<script>
  import Treeselect from '@riophae/vue-treeselect'
  import Unit from './Unit'
  import { doAdd, doEdit } from '@/api/basics/product'
  import { getList } from '@/api/basics/category'
  import { handleTree } from '@/utils/index'

  export default {
    name: 'ProductEdit',
    components: { Treeselect, Unit },
    data() {
      return {
        form: {
          productCode: undefined,
          productName: undefined,
          categoryId: undefined,
          spec: undefined,
          model: undefined,
          unitName: undefined,
          price: undefined,
        },
        rules: {
          productCode: [{ required: true, trigger: ['blur', 'change'], message: '请输入编码' }],
          productName: [{ required: true, trigger: ['blur', 'change'], message: '请输入名称' }],
          categoryId: [{ required: true, trigger: ['blur', 'change'], message: '请选择类别' }],
          spec: [{ required: false, trigger: ['blur', 'change'], message: '请输入规格' }],
          model: [{ required: false, trigger: ['blur', 'change'], message: '请输入型号' }],
          unitName: [{ required: true, trigger: ['blur', 'change'], message: '请输入单位' }],
          price: [{ required: true, trigger: ['blur', 'change'], message: '请输入单价' }],
        },
        title: '',
        dialogFormVisible: false,
        options: [],
      }
    },
    created() {
      this.getCategory()
    },
    methods: {
      saveUnitData(data) {
        if (data) {
          this.form.unitName = data.unitName
          this.form.unitId = data.unitId
        }
      },
      openUnit() {
        this.$refs.unit.showEdit()
      },
      async getCategory() {
        const { data } = await getList(this.queryForm)
        this.options = handleTree(data, 'categoryId', 'parentId', 'children', 0)
      },
      handleNodeClick(data) {
        this.form.categoryId = data.categoryId
        this.form.categoryName = data.categoryName
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.categoryId,
          label: node.categoryName,
          children: node.children,
        }
      },
      showEdit(row) {
        if (!row) {
          this.title = '新增'
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.productId) {
              await doEdit(this.form).then((res) => this.callbackFun(res))
            } else {
              await doAdd(this.form).then((res) => this.callbackFun(res))
            }
          } else {
            return false
          }
        })
      },
      callbackFun(res) {
        if (res.success) {
          this.$baseMessage(res.msg, 'success')
          this.$emit('fetch-data')
          this.close()
        } else {
          this.$baseMessage(res.msg, 'error')
        }
      },
    },
  }
</script>
